<?php

/**
 * 客户端向服务器端发送信息时，服务器端触发 onMessage 事件回调.
 * 服务器端可以调用 $server->push() 向某个客户端（使用 $fd 标识符）发送消息.
 */


//创建websocket服务器对象，监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server("0.0.0.0", 9502);

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "您好，请问有什么可以帮助您的吗？\n");
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    echo "{$frame->fd},接收到客户端的数据: {$frame->data}\n";
    $ws->push($frame->fd, "添加 qq 进行咨询");
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();

/**
 * 浏览器使用js向 websocket 发送数据
 */
?>
<script>
    let ws = new WebSocket("ws://127.0.0.1:9502");
    ws.onopen = function () {
        ws.send("Today is very good.");
    };
    ws.onmessage = function (evt) {
        console.log(evt.data)
    };
    ws.onclose = function (evt) {
        console.log("WebSocketClosed!");
    };
    ws.onerror = function (evt, e) {
        console.log("WebSocketError!" + evt.data);
    };
</script>